<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center">
				<div class="flex-start-center-wrap">
					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>
					<!--<jk-button class="margin-5-0" :loading="exportLoading" @click="onReportBtn">导出</jk-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :clearable="false" :option-list="workshopList" placeholder="区域" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange"></jk-select>
					<el-date-picker
						v-model="searchParams.belongDate"
						type="daterange"
						class="search-bar-item-size3 item-gap"
						range-separator="-"
						size="small"
						value-format="yyyy-MM-dd"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
					></el-date-picker>
					<el-select v-model="searchParams.scheduleShiftId" :disabled="!searchParams.belongDate" size="small" clearable placeholder="班次" class="search-bar-item-size3 margin-5-0 item-gap" @change="onScheduleShiftChange">
						<el-option
							v-for="item in scheduleShiftList"
							:key="item.id"
							:label="`${item.shiftName} (${item.beginTime} ~ ${item.endTime})`"
							:value="item.id"
						></el-option>
					</el-select>
					<jk-select v-model="searchParams.scheduleGroupId" :disabled="!searchParams.scheduleShiftId" :option-list="scheduleGroupList" value-key-name="id" label-key-name="groupName" placeholder="班组" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table ref="orderTable" border :stripe="false" :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-common-status v-if="item.keyName === 'auditState'" :status="scope.row.auditState"></jk-common-status>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="280">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-operation-bar
								:scope="scope"
								api-prefix="spinreport/lt-group-yield"
								:permission-prefix="prefix"
								@on-detail="onDetailBtn"
								@on-delete="onDeleteBtn"
								@on-edit="onEditBtn"
								@on-refresh="getListRequest"
							></jk-operation-bar>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="searchParams.count"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar, formatDate } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { orderPriorityList, orderStateList } from '../../../utils/jk/status-option-list';
    import permissionMixin from '../../../mixins/permission-mixin';
    import { workforcemanagementScheduleList } from '../../../api/schedule/scheduling';
    import { productionPrdReportGetDate } from '../../../api/production/xsReport';
    import { spinReportLtGroupYieldPage } from '../../../api/production/ltDailyGroupYieldNew';
    export default {
        name: 'LtGroupYieldStatistics',
        components: {
        },
        mixins: [calHeight, getMenuColumn, handlerCache, permissionMixin],
        data() {
            return {
                prefix: 'spinreport:ltGroupYield',
                apiItem: {
                    'page': spinReportLtGroupYieldPage
                },
                orderStateList: orderStateList,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                workshopList: [],
                scheduleShiftList: [],
                scheduleGroupList: [],
                searchParams: {
                    count: 0,
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    scheduleGroupId: null,
                    belongDate: [],
                    workshopId: null,
                    scheduleShiftId: null
                },
                moreSearchParams: {
                },
                selectItem: {},
                priorityList: orderPriorityList
            };
        },
        mounted() {
            this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
            this.getDependentData();
        },
        methods: {
            onAddBtn() {
                this.$toOtherRouter({ name: 'addLtGroupYieldStatistics' });
            },
            onDetailBtn(e) {
                this.dataId = e.id;
                this.$toOtherRouter({
                    name: 'detailLtGroupYieldStatistics',
                    query: {
                        id: this.dataId
                    }
                });
            },
            onEditBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'editLtGroupYieldStatistics',
                    query: {
                        id: this.dataId
                    }
                });
            },
            onDeleteBtn(row) {
                this.apiItem.delete({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            onWorkshopChange() {
                this.$set(this.searchParams, 'scheduleShiftId', null);
                this.$set(this.searchParams, 'scheduleGroupId', null);
                this.$set(this.searchParams, 'shiftId', null);
                this.$set(this.searchParams, 'shiftName', null);
                this.scheduleShiftList = [];
                this.getDateScheduleShiftOptionRequest();
            },
            onDateChange() {
                this.$set(this.searchParams, 'scheduleShiftId', null);
                this.$set(this.searchParams, 'scheduleGroupId', null);
                this.$set(this.searchParams, 'shiftName', null);
                this.$set(this.searchParams, 'shiftId', null);
                this.scheduleShiftList = [];
                this.getDateScheduleShiftOptionRequest();
            },
            getDateScheduleShiftOptionRequest() {
                if (this.searchParams.workshopId && this.searchParams.belongDate) {
                    return workforcemanagementScheduleList({
                        belongDate: [this.searchParams.belongDate, this.searchParams.belongDate],
                        workshopId: this.searchParams.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData && resData.length) {
                                this.scheduleShiftList = resData[0].scheduleShiftList;
                            }
                        }
                    });
                }
            },
            onScheduleShiftChange(e) {
                let item = {};
                if (e) {
                    item = this.scheduleShiftList.find(x => x.id === e);
                } else {
                    item = {
                        id: null,
                        shiftId: null,
                        shiftName: null,
                        scheduleId: null
                    };
                }
                this.$set(this.searchParams, 'scheduleGroupId', null);
                this.scheduleGroupList = item.scheduleGroupList;
                this.$set(this.searchParams, 'scheduleId', item.scheduleId);
                this.$set(this.searchParams, 'scheduleShiftId', item.id);
                this.$set(this.searchParams, 'shiftId', item.shiftId);
                this.$set(this.searchParams, 'shiftName', item.shiftName);
                this.getOpenMachineListRequest();
            },
            getOpenMachineListRequest() {
                if (this.searchParams.workshopId && this.searchParams.processId && this.searchParams.belongDate && this.searchParams.scheduleShiftId) {
                    this.tableLoading = true;
                    productionPrdReportGetDate({
                        workshopId: this.searchParams.workshopId,
                        processId: this.searchParams.processId,
                        scheduleShiftId: this.searchParams.scheduleShiftId,
                        belongDate: this.searchParams.belongDate
                    }).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.$set(this.searchParams, 'prdReportMachineList', res.data.res);
                            this.calTotal();
                        }
                    });
                }
            },
            clearRadioRowEvent() {
                this.selectItem = {};
                this.$refs.orderTable.$refs.xTable.clearRadioRow();
            },
            onResetSearchBtn() {
                Object.assign(this.$data.moreSearchParams, this.$options.data().moreSearchParams);
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onFinish() {
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                // this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                await this.getMenuColumnListRequest();
                await this.getDateScheduleShiftOptionRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem.page(params);
                }).then(res => {
                    this.exportLoading = false;
                    if (res.data.status === 200) {
                        import('@/vendor/Export2Excel').then(excel => {
                            const tHeader = this.tableColumnList.map(x => x.title);
                            const filterVal = this.tableColumnList.map(x => x.keyName);
                            const list = JSON.parse(JSON.stringify(res.data.res.itemList)).map(item => {
                                return item;
                            });
                            const data = this.formatJson(filterVal, list);
                            excel.export_json_to_excel({
                                header: tHeader,
                                data,
                                filename: `${res.data.res.workshopName}-${res.data.res.shiftName}-${res.data.res.groupName}-${this.searchParams.belongDate}`,
                                autoWidth: true,
                                bookType: 'xlsx'
                            });
                        });
                    }
                }).catch(() => {});
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            },
            /** 查询列表 */
            getListRequest() {
                if (this.searchParams.workshopId) {
                    this.tableLoading = true;
                    this.selectItem = {};
                    const params = { ...this.moreSearchParams, ...this.searchParams };
                    return this.apiItem['page'](params).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.tableData = res.data.res;
                            this.searchParams.count = res.data.count;
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', '区域不能为空!');
                }
            }
        }
    };
</script>
